package webs.servlet.ServletDemoThree;

//生成验证码
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkImg")
public class servletCheckImg extends HttpServlet
{
    public static String str=null;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        int width = 100;
        int height = 30;
        //做一张验证码
        //1.生成一张图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //2.美化图片
        //2.1 填充,设置笔的颜色
        Graphics pen = image.getGraphics();
        pen.setColor(Color.pink);
        pen.fillRect(0, 0, width, height);

        //2.2 画边框，蓝色边框
        pen.setColor(Color.blue);
        pen.drawRect(0, 0, width - 1, height - 1);

        //2.3 写验证码内容
        String conText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        str = new String();
        Random rand = new Random();
        for (int i = 0; i < 4; i++)
        {
            int index = rand.nextInt(62);
            str = str + String.valueOf(conText.charAt(index));
            pen.drawString(String.valueOf(conText.charAt(index)), 20 * (i + 1), height / 2);
        }
        //2.3画干扰线
        pen.setColor(Color.black);
        for (int i = 1; i <= 6; i++)
        {
            int x1 = rand.nextInt(width);
            int x2 = rand.nextInt(width);
            int y1 = rand.nextInt(height);
            int y2 = rand.nextInt(height);
            pen.drawLine(x1, y1, x2, y2);
        }
        //3.将图片输出到流
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
}
